﻿using System;
using QRCoder;
using System.IO;
using System.Drawing;

namespace Base.Core.QRCode
{
    public class QRCodeEncoder
    {
        /// <summary>
        /// 返回图片
        /// </summary>
        /// <param name="message"></param>
        /// <param name="version"></param>
        /// <param name="pixel"></param>
        /// <param name="icon_path"></param>
        /// <param name="icon_size"></param>
        /// <param name="icon_border"></param>
        /// <param name="white_edge"></param>
        /// <returns></returns>
        public static Bitmap Encode(string message, int version, int pixel, string icon_path, int icon_size, int icon_border, bool white_edge)
        {
            QRCodeGenerator qRCodeEncoder = new QRCodeGenerator();
            QRCodeData codeData = qRCodeEncoder.CreateQrCode(message, QRCodeGenerator.ECCLevel.M, true, true, QRCodeGenerator.EciMode.Utf8, version);
            QRCoder.QRCode code = new QRCoder.QRCode(codeData);
            Bitmap icon = null;
            if (!string.IsNullOrEmpty(icon_path))
                icon = new Bitmap(icon_path);
            Bitmap bmp = code.GetGraphic(pixel, Color.Black, Color.White, icon, icon_size, icon_border, white_edge);
            return bmp;
        }
        /// <summary>
        /// 返回保存路径
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string Encode(string Sn)
        {
            QRCodeGenerator qRCodeEncoder = new QRCodeGenerator();
            QRCodeData codeData = qRCodeEncoder.CreateQrCode(Sn, QRCodeGenerator.ECCLevel.M, true, true, QRCodeGenerator.EciMode.Utf8, 5);
            QRCoder.QRCode code = new QRCoder.QRCode(codeData);
            Bitmap bmp = code.GetGraphic(7);
            var fileName = Sn + ".png";
            var fullPath = Path.Combine(GlobalEnvironment.PhotoStorageUrl, fileName);
            if (File.Exists(fullPath))
                return fileName;
            bmp.Save(fullPath, System.Drawing.Imaging.ImageFormat.Png);
            //释放资源
            bmp.Dispose();
            code.Dispose();
            codeData.Dispose();
            qRCodeEncoder.Dispose();
            return fileName;
        }
    }
}
